const querystring = require('querystring')
const router = require('./router')

const getPostData = (req) => {
  const promise = new Promise((resovle, reject) => {
    if (req.method !== 'POST') {
      resovle({})
      return;
    }
    if (req.headers['content-type'] !== 'application/json') {
      resovle({})
      return;
    }
    let tempData = '';
    req.on('data', chunk => {
      tempData += chunk.toString();
    })
    req.on('end', () => {
      if (!tempData) {
        resovle({});
        return;
      }
      resovle(
        JSON.parse(tempData)
      )
    })
  })
  return promise;
}

const serverHandle = (req, res) => {
  const url = req.url;
  req.path = url.split('?')[0];
  req.query = querystring.parse(url.split('?')[1]);
  res.setHeader('Content-Type', 'application/json')
  getPostData(req).then(async reqdata => {
    req.body = reqdata
    const resData = await router(req, res);
    console.log(resData, 123)
    if (resData) {
      res.end(
        JSON.stringify(resData)
      )
      return
    }
    res.writeHeader(400, { 'Content-Type': 'text/plain' })
    res.write('400 NOT FOUND')
    res.end()
  })
}


module.exports = serverHandle;